package com.charlotte.study.gupao.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author junjie.ding
 */
public class MyBlockingQueue {

    private final Lock lock = new ReentrantLock();

    private Condition notFull = lock.newCondition();

    private Condition notEmpty = lock.newCondition();

    Object[] items;

    private int takeIndex;

    private int putIndex;

    private int count;

    public MyBlockingQueue(){
        this(10);
    }

    public MyBlockingQueue(int size) {
        items = new Object[size];
    }


    private void checkIfNull(Object item){
        if(item == null){
            throw new NullPointerException();
        }
    }

    public void put(Object item){
        checkIfNull(item);
        try {
            this.lock.lockInterruptibly();
            while(count == items.length){
                // 队列已经满，阻塞生产者
                notFull.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            this.lock.unlock();
        }

    }

}
